package com.lvsc.sdaplacefinder.util;

import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;

import android.util.Log;

public class JSONParserUtil {
	private static final String TAG = JSONParserUtil.class.getName();
	private static ObjectMapper instance;

	public static ObjectMapper getMapper() {
		if (instance != null)
			return instance;

		ObjectMapper mapper = new ObjectMapper().setVisibility(
				JsonMethod.FIELD, Visibility.ANY);
		new ObjectMapper();
		mapper.configure(
				DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		return mapper;
	}

	public static <T> List<T> parseList(String json, Class<T> clazz) {
		ObjectMapper mapper = getMapper();

		JavaType listType = mapper.getTypeFactory().constructCollectionType(
				ArrayList.class, clazz);

		List<T> list = null;
		try {
			list = mapper.readValue(json, listType);
		} catch (Exception e) {
			Log.e(TAG, "parseList", e);
		}

		return list;
	}

	public static <T> T parseObject(String json, Class<T> clazz) {
		ObjectMapper mapper = getMapper();
		T object = null;
		try {
			object = mapper.readValue(json, clazz);
		} catch (Exception e) {
			Log.e(TAG, "parse", e);
		}
		return object;
	}

}
